/***
 * Copyright (c) 2010 readyState Software Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package fr.enseirb.mycub.component.map.bus;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;

import fr.enseirb.mycub.R;
import fr.enseirb.mycub.component.map.BalloonOverlayViewStations;
import fr.enseirb.mycub.db.BusDBConstants;
import fr.enseirb.mycub.db.BusDBHelper;
import fr.enseirb.mycub.db.DBAdapter;
import fr.enseirb.mycub.db.StationsProvider;
import fr.enseirb.mycub.service.LocationService;
import fr.enseirb.mycub.structures.SpecificLine;
import fr.enseirb.mycub.utils.Utils;

/**
 * A view representing a MapView marker information balloon.
 * <p>
 * This class has a number of Android resource dependencies:
 * <ul>
 * <li>drawable/balloon_overlay_bg_selector.xml</li>
 * <li>drawable/balloon_overlay_close.png</li>
 * <li>drawable/balloon_overlay_focused.9.png</li>
 * <li>drawable/balloon_overlay_unfocused.9.png</li>
 * <li>layout/balloon_map_overlay.xml</li>
 * </ul>
 * </p>
 * 
 * @author Jeff Gilfelt
 * 
 */
public class BalloonOverlayViewStationsBus<Item extends OverlayItem> extends  BalloonOverlayViewStations<Item> {

	private LinearLayout mLinearLayout;
	private TextView mTextViewTitle;
	private TextView mClosedTextView;
	private TextView mDistanceTextView;
	private TextView mSpecialTextView;
	private CheckBox mFavoriteCheckBox;
	private Context mContext;
	private String mId;

	/**
	 * Create a new BalloonOverlayView.
	 * 
	 * @param context
	 *            - The activity context.
	 * @param balloonBottomOffset
	 *            - The bottom padding (in pixels) to be applied when rendering
	 *            this view.
	 */
	public BalloonOverlayViewStationsBus(Context context, int offset) {
		super(context, offset);
		mContext = context;
		mLinearLayout = new LinearLayout(context);
		mLinearLayout.setVisibility(VISIBLE);
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.balloon_bike_overlay, mLinearLayout);
		mSpecialTextView = (TextView) v.findViewById(R.id.balloon_text);
		mTextViewTitle = (TextView) v.findViewById(R.id.balloon_name);
		mClosedTextView = (TextView) v.findViewById(R.id.balloon_closed);
		mDistanceTextView = (TextView) v.findViewById(R.id.balloon_distance);
		mFavoriteCheckBox = (CheckBox) v
				.findViewById(R.id.balloon_item_favorite);
		//TODO gestion des favoris
		//		mFavoriteCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
		//			
		//			@Override
		//			public void onCheckedChanged(CompoundButton checkBox, boolean checked) {
		//				BikeDBHelper.updateFavorite(DBAdapter.getInstance(mContext).getDB(),Integer.parseInt(mId), checked);
		//			}
		//		});
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.NO_GRAVITY;
		addView(mLinearLayout, params);

	}

	/**
	 * Sets the view data from a given overlay item.
	 * 
	 * @param item
	 *            - The overlay item containing the relevant view data (title
	 *            and snippet).
	 */
	public void setData(Item item, Location location) {
		mId = String
				.valueOf(((BusStationOverlay) item)
						.getId());
		Cursor station = ((Activity) mContext).managedQuery(Uri
				.withAppendedPath(StationsProvider.CONTENT_BUS_URI, mId), new String[] {
			BusDBConstants.KEY_NAME, BusDBConstants.KEY_OPEN,
			BusDBConstants.KEY_FAVORITE }, null, null, null);

		DBAdapter adapter =  DBAdapter.getInstance(mContext);

		ArrayList<SpecificLine> lines = BusDBHelper.getSpecificLineLinkedToStation(
				adapter.getDB(), ((BusStationOverlay) item).getId(),new String[] {
					BaseColumns._ID, BusDBConstants.KEY_NAME});

		LinearLayout linesLayout = (LinearLayout) findViewById(R.id.layout_lines_icones);
		Pattern intsOnly = Pattern.compile("([\\+-]?\\d+)([eE][\\+-]?\\d+)?");
//		String ligneText = "lignes :";

		for(int i = 0; i < lines.size(); i++){
//			Log.i("Overlay : ", "LIGNE -> "+lines.get(i).name+" ( id : "+lines.get(i).id+" ) ");
//			ligneText += lines.get(i).name;
			Hashtable<String, BitmapDrawable> table = BusStationsOverlay.getTable(mContext);
			
			Matcher makeMatch = intsOnly.matcher(lines.get(i).name);
			makeMatch.find();
			String inputInt = makeMatch.group();
//			Log.i("Overlay : ", "LIGNE found : "+inputInt);
			BitmapDrawable drawable = table.get(inputInt);
			
			if(drawable == null) continue;
			ImageView icone = new ImageView(mContext);
			icone.setImageDrawable(drawable);
			icone.setMaxWidth(50);
			icone.setMaxHeight(50);
			icone.setAdjustViewBounds(true);
			linesLayout.addView(icone);
		}

//		mSpecialTextView.setText(ligneText);
//		mSpecialTextView.setVisibility(View.VISIBLE);
		
		
		mLinearLayout.setVisibility(VISIBLE);
		String name = station.getString(station
				.getColumnIndex(BusDBConstants.KEY_NAME));
		mTextViewTitle.setText(name);

		if (station.getInt(station
				.getColumnIndex(BusDBConstants.KEY_FAVORITE)) == 1) {
			mFavoriteCheckBox.setChecked(true);
		} else {
			mFavoriteCheckBox.setChecked(false);
		}

		if (station.getInt(station.getColumnIndex(BusDBConstants.KEY_OPEN)) == 1) {
			// Opened station
			mClosedTextView.setVisibility(GONE);
		} else {
			// Closed station
			mClosedTextView.setVisibility(VISIBLE);
		}
		GeoPoint point = item.getPoint();
		Log.i("BalloonOverlay", " geopoint : "+point.toString());
		int distance = Utils.computeDistance(point.getLatitudeE6(), point.getLongitudeE6(), location);
		Log.i("BalloonOverlay", " distance : "+distance);
		if (distance == LocationService.DISTANCE_UNAVAILABLE) {
			// No distance to show
			mDistanceTextView.setVisibility(GONE);
		} else {
			// Show distance
			mDistanceTextView.setVisibility(VISIBLE);
			mDistanceTextView.setText(mContext.getString(R.string.at) + " " + Utils.formatDistance(distance));
		}
	}

	protected void showStationDetails(Uri uri) {
		//		Intent intent = new Intent(mContext, StationDetailsActivity.class)
		//				.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		//		intent.setAction(Intent.ACTION_VIEW);
		//		intent.setData(uri);
		//		mContext.startActivity(intent);
	}

	protected void showStationDetails(String id) {
		//		showStationDetails(Uri.withAppendedPath(StationsProvider.CONTENT_URI,
		//				id));
	}

}
